const basePath = getRootPath();
const contextPath = getContextPath();

layui.use(["form","laypage","layer","table","element","upload"], function() {



    var table = layui.table;
    var form = layui.form;
    var laypage = layui.laypage;
    var layer = layui.layer;
    var element = layui.element;
    var upload = layui.upload;

    // 参考https://www.yht7.com/news/89785，解决table.checkStatus()解析不了的问题
    // tableData不需要了，根本原因是layui.js要放在工程路径下
    // var tableData;
    //方法级渲染
    table.render({
        elem: '#LAY_table_user',
        url: contextPath + 'BookController/getBooks',
        done: function (res, curr, count) { //表格数据加载完后的事件
            //调用示例
            // layer.photos({//点击图片弹出
            //     photos: '.layer-photos-demo',
            //     anim: 1 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
            // });

        },
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'id', title: 'id', width: 150, sort: true, fixed: true},
            {field: 'name', title: '书名', width: 150, sort: true, edit: true},
            {field: 'count', title: '剩余数量', width: 150, sort: true, edit: true},
            {
                field: 'bookPath', title: '图片', width: 110, templet: function (d) {
                    var bookpath = basePath + d.bookPath;
                    return '<div class="layer-photos-demo" style="cursor:pointer;">' +
                        '<img  src="' + bookpath + '" width="80px" height="100px"></div>';
                }
            },
            {field: 'right', title: '操作', width: 350, toolbar: "#barDemo"}
        ]],
        id: 'testReload',
        page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //自定义分页布局
            //,curr: 5 //设定初始在第 5 页
            groups: 1, //只显示 1 个连续页码
            first: false, //不显示首页
            last: false, //不显示尾页
            limit: 2,
            limits: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        }
    });
    var $ = layui.$;
    $('.demoTable .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //这是layui所有除了表格按钮之外的按钮监听实现处，属性与button的data-type属性相对应
    active = {
        //搜索按钮 key的值是搜索框的值
        reload: function () {
            var demoReload = $('#demoReload');
            //传入搜索值
            table.reload('testReload', {
                where: {
                    key: demoReload.val()
                }
            });
        },
        //多行删除
        delSelect: function () {
            //获取选中数据
            var checkStatus = table.checkStatus('testReload')
            var data = checkStatus.data;
            if (checkStatus.data.length == 0) {
                layer.msg('请选择要删除的数据', {icon: 5});
                return;
            }

            //询问框
            layer.confirm('是否删除选中的数据？', {
                btn: ['删除', '取消'] //按钮
            }, function () {
                var ids = "";
                //这里先遍历，然后到后台处理
                for (var i = 0; i < data.length; i++) {
                    ids += data[i].id + ";";
                }
                $.ajax({
                    url: basePath + "BookController/deleteBooks",
                    type: "post",
                    data: {"ids": ids},
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            layer.msg("删除成功", {icon: 6});
                            table.reload('testReload', {
                                where: {
                                    key: ""
                                }
                            });
                        } else {
                            layer.msg("删除失败", {icon: 5});
                        }
                    }
                });
            }, function () {
                layer.closeAll();
            });
        },
        //把表格转化成Excel文件(文件上传下载这部分慎用，没有深入研究)
        download: function () {
            $.ajax({
                url: "servlet/BookController",
                data: {"memthodname": "BookExport"},
                type: "GET",
                dataType: "json",
                success: function (data) {
                    if (data.data) {
                        layer.msg("导出成功", {icon: 6});
                    } else {
                        layer.msg("导出失败", {icon: 5});
                    }
                }
            });
        },
        upload: function () {
            var filePath = $('#file').val();
            if (filePath == "") {
                layer.msg("请选择文件之后在导入", {icon: 5});
                return;
            }
            //alert(filePath);
            $.ajax({
                url: "servlet/BookController",
                data: {"memthodname": "BookImport", "filePath": filePath},
                type: "GET",
                dataType: "json",
                success: function (data) {
                    if (data.data) {
                        layer.msg("导入成功", {icon: 6});
                        table.reload('testReload', {
                            where: {
                                key: ""
                            }
                        });
                    } else {
                        layer.msg("导入失败", {icon: 5});
                    }
                }
            });
        }

    };
    //监听单元格编辑 dataTable 对应 <table> 中的 lay-filter="dataTable"
    table.on('edit(dataTable)', function (obj) {
        var value = obj.value, //得到修改后的值
            data = obj.data, //得到所在行所有键值
            field = obj.field; //得到字段
        //layer.msg('[ID: '+ data.userId +'] ' + field + ' 字段更改为：'+ value);
        var url = "";
        if(field == 'name') {
            url = basePath + "BookController/editBookName";
        } else if(field == 'count') {
            url = basePath + "BookController/editBookCount"
        }
        $.ajax({
            url: url,
            type: "POST",
            // 偷懒，不想写两遍ajax，干脆把value赋给所有可能edit的列
            data: {"id": data.id, "count": value, "name": value},
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    //同步更新表格和缓存对应的值
                    layer.msg("修改成功", {icon: 6});
                } else {
                    layer.msg("修改失败", {icon: 5});
                }
            }

        });

    });
    table.on('tool(dataTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'borrowBook') {
            var body;
            layer.open({
                type: 2,
                title: '' +
                    '<li id="icon" class="layui-icon layui-icon-release layui-anim layui-anim-scaleSpring" ' +
                    'style="font-size: 30px; color: #009688;" data-anim="layui-anim-scaleSpring"></li> 编辑 ',

                shadeClose: true,
                shade: false,
                btn: ['添加'],
                btnAlign: 'c',
                maxmin: true, //开启最大化最小化按钮
                area: ['470px', '500px'],//area: [window.screen.width / 2 + 'px', window.screen.height / 2 + 'px'], //宽高
                content: contextPath + "dialog.html",
                success: function (layero, index) {
                    body = layer.getChildFrame('body', index);
                    body.find("input#bookname").val(data.name);
                },
                yes: function (layero, index) {
                    var userName = body.find("input#username").val();
                    var stuName = body.find("input#stuname").val();
                    var bookName = body.find("input#bookname").val();
                    if (userName == null) {
                        layer.msg("用户名不能为空", {icon: 5});
                        return;
                    }
                    $.ajax({
                        url: basePath + "BookController/addBorrow",
                        type: "post",
                        data: {
                            "stuId": userName,
                            "bookId": data.id
                        },
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 0) {
                                layer.alert('借书成功!', function () {
                                    layer.closeAll();
                                    table.reload('testReload', {
                                        where: {
                                            key: ""
                                        }
                                    });
                                });
                            } else {
                                layer.msg("借书失败", {icon: 5});
                            }
                        }
                    });
                }
            });
        } else if (obj.event === 'returnBook') {


        } else if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                console.log(data);
                $.ajax({
                    url: basePath + "BookController/deleteBooks",
                    type: "post",
                    data: {"ids": "" + data.id + ";"},
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            obj.del();
                            layer.close(index);
                            layer.msg("删除成功", {icon: 6});
                        } else {
                            layer.msg("删除失败", {icon: 5});
                        }
                    }

                });
            });
        } else if (obj.event === 'edit') {
            layer.prompt({
                formType: 2
                , title: '修改 [' + data.name + '] 的数量'
                , value: data.count
            }, function (value, index) {
                $.ajax({
                    url: basePath + "BookController/editBookCount",
                    type: "POST",
                    // 此处和上面的功能重复，上面的edit(dataTable)可以直接在表格里改数量
                    data: {"id": data.id, "count": value},
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            //同步更新表格和缓存对应的值
                            layer.msg("修改成功", {icon: 6});
                        } else {
                            layer.msg("修改失败", {icon: 5});
                        }
                    }

                });
            });
        }
    });
});